﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DataBase;
using System.IO;

public class DialogueText : MonoBehaviour
{
    #region 字段
    /// <summary>
    /// 这一句是否真正完成
    /// </summary>
    private bool isDialogue;

    /// <summary>
    /// 这一行是否读完
    /// </summary>
    private bool isAllSet;

    /// <summary>
    /// UI中的头像
    /// </summary>
    private Image headIcon;
    /// <summary>
    /// UI中的文本
    /// </summary>
    private Text contentText;
    private Transform backGround;

    /// <summary>
    /// 当前是第几句话
    /// </summary>
    int currentCount;
    /// <summary>
    /// 当前话的人
    /// </summary>
    int currentName;
    /// <summary>
    /// 当前话可能引发的事件
    /// </summary>
    int currentEvent;
    /// <summary>
    /// 当前话的内容
    /// </summary>
    string currentContent;

    private bool isFinal;

    /// <summary>
    /// 储存所有头像的字典
    /// </summary>
    private Dictionary<int, Sprite> HeadIcons = new Dictionary<int, Sprite>();

    #endregion

    private void Awake()
    {
        headIcon = this.transform.Find("Head").GetComponent<Image>();
        contentText = this.transform.Find("Content").GetComponent<Text>();
        backGround = this.transform.Find("Background");

        Dialogue.initData();//初始化、缓存对话内容
        InitAllHeadIcon();//初始化、缓存头像
        isDialogue = false;
        EventCenter.AddListener<int>(MyEventType.Dialogue, StartDialogue);
    }

    private void StartDialogue(int Key)
    {
        StartCoroutine("GetDialogue", Key);
    }

    private IEnumerator GetDialogue(int Key)
    {
        backGround.gameObject.SetActive(true);
        headIcon.gameObject.SetActive(true);
        contentText.gameObject.SetActive(true);
        //还应该有停止玩家所有输入
        Dialogue currentDialogue = Dialogue.get(Key);
        int Count = currentDialogue.Name.Length;
        currentCount = 0;
        currentName = 0;
        currentEvent = 0;
        currentContent = "";
        isDialogue = false;
        isFinal = false;

        while (currentCount < Count)
        {
            if (isDialogue)
            {
                yield return null;
            }
            else
            {
                currentName = currentDialogue.Name[currentCount];
                currentEvent = currentDialogue.Event[currentCount];
                currentContent = currentDialogue.Content[currentCount];

                headIcon.overrideSprite = HeadIcons[currentName];

                StartCoroutine("TypeText",currentContent);
                isDialogue = true;
                currentCount++;
                if(currentCount==Count)
                {
                    isFinal = true;
                }
            }
        }
    }

    /// <summary>
    /// 显示一句话
    /// </summary>
    /// <param name="content">这句话内容</param>
    /// <returns></returns>
    public IEnumerator TypeText(string content)
    {
        float tpyeInterval = 0.075f;
        isAllSet = false;
        contentText.text = "";
        foreach(char letter in content.ToCharArray())
        {
            contentText.text += letter;
            yield return new WaitForSeconds(tpyeInterval);
        }

        EventCenter.Broadcast<int>(MyEventType.DialogueEvent, currentEvent);
        isAllSet = true;
    }

    private void Update()
    {
        if(isDialogue)
        {
            if(Input.GetKeyDown(KeyCode.Space))
            {
                if (isAllSet)
                {
                    if(isFinal)
                    {
                        backGround.gameObject.SetActive(false);
                        headIcon.gameObject.SetActive(false);
                        contentText.gameObject.SetActive(false);
                    }
                    isDialogue = false;
                }
                else
                {
                    StopCoroutine("TypeText");
                    contentText.text = currentContent;
                    isAllSet = true;
                }
            }
        }

    }

    /// <summary>
    /// 自动加载HeadIcon文件夹下所有头像，按照名称存储在字典HeadIcon中
    /// </summary>
    private void InitAllHeadIcon()
    {
        List<string> headIconName = new List<string>();
        string filePath = @"Assets\Resources\HeadIcon";
        if(Directory.Exists(filePath))
        {
            DirectoryInfo direction = new DirectoryInfo(filePath);
            FileInfo[] files = direction.GetFiles("*", SearchOption.AllDirectories);

            for(int i=0;i<files.Length;i++)
            {
                if(files[i].Name.EndsWith(".png"))
                {
                    headIconName.Add(files[i].Name);
                }
            }
        }

        foreach(string name in headIconName)
        {
            Sprite tmpsprite = null;
            string headPath = @"HeadIcon\" + name.Replace(".png", "");

            Texture2D HeadIcon = Resources.Load(headPath) as Texture2D;
            tmpsprite = Sprite.Create(HeadIcon, new Rect(0, 0, HeadIcon.width, HeadIcon.height), new Vector2(0.5f, 0.5f));

            HeadIcons.Add(int.Parse(name.Replace(".png", "")), tmpsprite);
        }
    }
}
